package cn.yzj.openapi.controller;

import cn.yzj.openapi.common.FinalResult;
import cn.yzj.openapi.dao.intf.ShortUrlDao;
import cn.yzj.openapi.dao.intf.TiebaSignDao;
import cn.yzj.openapi.dto.EpidemicQueryDTO;
import cn.yzj.openapi.dto.TiebaSignDTO;
import cn.yzj.openapi.dto.UrlDTO;
import cn.yzj.openapi.service.EpidemicService;
import cn.yzj.openapi.service.RandomImgService;
import cn.yzj.openapi.service.UrlService;
import cn.yzj.openapi.utils.ReturnResultUtils;
import com.google.common.cache.Cache;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * 短链接控制器
 *
 * @author gzkemays
 * @since 2021/11/11 16:36
 */
@RestController
@RequestMapping("/openapi")
public class OpenApiController {
  @Resource ShortUrlDao shortUrlDao;
  @Resource TiebaSignDao tiebaSignDao;
  @Resource UrlService urlService;
  @Resource RandomImgService randomImgService;
  @Resource EpidemicService epidemicService;

  @Resource(name = "sfCache")
  Cache<String, String> sfCache;

  @PostMapping("/shortUrl")
  public FinalResult getShortUrl(@Valid UrlDTO dto) {
    return ReturnResultUtils.simple(shortUrlDao.generateShortUrl(dto));
  }

  @PostMapping("/sfCookie")
  public FinalResult setSfCookie(String cookie) {
    sfCache.put("cookie", cookie);
    return ReturnResultUtils.simple(null);
  }

  @RequestMapping(
      path = "/epidemic",
      method = {RequestMethod.GET, RequestMethod.POST})
  public FinalResult epidemic(@Valid EpidemicQueryDTO dto) {
    return ReturnResultUtils.simple(epidemicService.getEpidemic(dto));
  }

  @GetMapping(path = {"/epidemic/{area}/{city}"})
  public FinalResult restFulEpidemic(
      @PathVariable String area, @PathVariable(required = false) String city) {
    EpidemicQueryDTO dto = new EpidemicQueryDTO(area, city);
    return ReturnResultUtils.simple(epidemicService.getEpidemic(dto));
  }

  @GetMapping("/epidemic/{position}")
  public FinalResult epidemic(@PathVariable String position) {
    return ReturnResultUtils.simple(epidemicService.getEpidemic(position));
  }

  @PostMapping("/redirect")
  public FinalResult getTruthRedirect(@Valid UrlDTO dto) {
    return ReturnResultUtils.simple(urlService.getRedirectUrl(dto.getUrl()));
  }

  @PostMapping("/tieba/sign")
  public FinalResult tiebaSign(@Valid TiebaSignDTO dto) {
    return ReturnResultUtils.simple(tiebaSignDao.save(dto));
  }

  @PostMapping("/tieba/check")
  public FinalResult tiebaCheck(String username) {
    return ReturnResultUtils.simple(tiebaSignDao.checkSign(username));
  }

  @GetMapping("/randomImg")
  public FinalResult getRandomImg() {
    return ReturnResultUtils.simple(randomImgService.getRandomImg());
  }
}
